package com.spark.forkJoin;

import java.time.LocalTime;
import java.util.Calendar;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;
import java.util.stream.Stream;

public class ForkJoinCalculator {

    public static class SumTask extends RecursiveTask<Long> {
        private long[] numbers;
        private int from;
        private int to;

        public SumTask(long[] numbers, int from, int to) {
            this.numbers = numbers;
            this.from = from;
            this.to = to;
        }

        @Override
        protected Long compute() {
            if (to - from < 10) {
                long total = 0;
                for (int i = from; i <= to; i++) {
                    total += i;
                }
                return total;
            } else {
                int middle = (from + to) / 2;
                SumTask taskLeft = new SumTask(numbers, from, middle);
                SumTask taskRight = new SumTask(numbers, middle + 1, to);
                taskLeft.fork();
                taskRight.fork();
                return taskLeft.join() + taskRight.join();
            }
        }
    }

    public static void main(String[] args) {
        long begin = Calendar.getInstance().getTimeInMillis();
        //Runtime.getRuntime().availableProcessors(),获取CPU核心数
        ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
        long value = pool.invoke(new SumTask(LongStream.rangeClosed(0, 10000000).toArray(), 0, 10000000));
        long end = Calendar.getInstance().getTimeInMillis();
        System.out.println("-----------------------");
        System.out.println(end - begin);
        System.out.println(value);
    }
}
